<?php
/**
 * This file is form http://findcat.cn
 *
 * @link     https://findcat.cn
 * @email    1476982312@qq.com
 */
namespace App\Console\Commands;

use Carbon\Carbon;
use App\Mail\CommonReport;
use App\Models\BirthdayTool;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Overtrue\ChineseCalendar\Calendar;

class BirthdayToolCommand extends Command
{
    /**
     * @var string
     */
    protected $signature = 'blog:birthday_tool';

    /**
     * @var string
     */
    protected $description = '小工具：生日订阅检查';

    /**
     * LaravelFanerBlogInstallCommand constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $calendar = new Calendar();

        //新历时间
        $newCalendar = Carbon::now();
        //农历时间
        $lunarCalendar = $calendar->solar(Carbon::now()->year, Carbon::now()->month, Carbon::now()->day);

        //农历生日到达
        BirthdayTool::query()
            ->whereMonth('lunar_calendar', $lunarCalendar['lunar_month'])
            ->whereDay('lunar_calendar', $lunarCalendar['lunar_day'])
            ->chunk(10, function ($lunarCalendarBegins) {
                foreach ($lunarCalendarBegins as $lunarCalendarBegin) {
                    try {
                        $this->sendMessage($lunarCalendarBegin, '农历');
                    } catch (\Exception $exception) {
                        Log::debug($exception->getMessage());
                    }
                }
            });

        //新历生日到达
        BirthdayTool::query()
            ->whereMonth('new_calendar', $newCalendar->month)
            ->whereDay('new_calendar', $newCalendar->day)
            ->chunk(10, function ($newCalendarBegins) {
                foreach ($newCalendarBegins as $newCalendarBegin) {
                    try {
                        $this->sendMessage($newCalendarBegin, '新历');
                    } catch (\Exception $exception) {
                        Log::debug($exception->getMessage());
                    }
                }
            });
    }

    /**
     * 发送消息.
     *
     * @param       $birthdayBegin
     * @param mixed $isLunar
     */
    private function sendMessage($birthdayBegin, $isLunar)
    {
        $mail = new Mail();

        $message = <<<HTML
<div class="container" style="text-align: center">
    <h3 class="title">犯二青年博客-生日提醒小工具</h3>
    <span>
    今天是 <b>{$birthdayBegin->name}</b> 的 <b>{$isLunar}</b> 生日啦，礼物买了没？没买赶紧和朋友说声生日快乐吧！
</span>
</div>
HTML;

        //todo 这里到时候把邮箱关联到账号去
        $mail::to(config('mail.mailException.toAccounts', []))->send(new CommonReport($message, '朋友生日提醒'));
    }
}
